<template>
  <el-dialog 
    v-model="dialogVisible" 
    :title="title"
    :width="width"
    destroy-on-close
    class="custom-dialog"
    v-bind="$attrs"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-width="100px"
      label-position="right"
      class="form-container"
    >
      <slot></slot>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">{{ cancelText }}</el-button>
        <el-button type="primary" @click="submit" :loading="loading">
          {{ confirmText }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, watch } from 'vue'

export default {
  name: 'FormDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '表单'
    },
    width: {
      type: String,
      default: '500px'
    },
    loading: {
      type: Boolean,
      default: false
    },
    formModel: {
      type: Object,
      required: true
    },
    rules: {
      type: Object,
      default: () => ({})
    },
    cancelText: {
      type: String,
      default: '取消'
    },
    confirmText: {
      type: String,
      default: '确认'
    }
  },
  emits: ['update:visible', 'cancel', 'submit'],
  setup(props, { emit, expose }) {
    const formRef = ref(null)
    const dialogVisible = ref(props.visible)
    
    // 监听props.visible变化
    watch(() => props.visible, (val) => {
      dialogVisible.value = val
    })
    
    // 监听dialogVisible变化
    watch(() => dialogVisible.value, (val) => {
      emit('update:visible', val)
    })
    
    // 取消
    const cancel = () => {
      dialogVisible.value = false
      emit('cancel')
    }
    
    // 提交
    const submit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        emit('submit', props.formModel)
      } catch (error) {
        console.error('表单验证失败:', error)
      }
    }
    
    // 重置表单
    const resetForm = () => {
      if (formRef.value) {
        formRef.value.resetFields()
      }
    }
    
    // 暴露方法给父组件
    expose({
      formRef,
      resetForm,
      validate: async () => {
        if (!formRef.value) return false
        return formRef.value.validate()
      }
    })
    
    return {
      formRef,
      dialogVisible,
      cancel,
      submit
    }
  }
}
</script>

<style scoped>
.custom-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #eee;
  padding: 16px 20px;
}

.custom-dialog :deep(.el-dialog__footer) {
  border-top: 1px solid #eee;
  padding: 16px 20px;
}

.form-container {
  padding: 20px 0;
}

.el-dialog {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input), :deep(.el-select), :deep(.el-date-editor) {
  width: 100%;
}
</style> 